package cs342.project1.mathNotebook.data;
import java.io.*;
import java.util.zip.*;

public class CompressionDecompressionHandler {
public static int bufferSize = 8192;

  public static void Compress(String filename) {
    // create output stream
    String zipname;

    zipname = filename.substring(0, filename.length() - 4)+".gz";
    System.out.println("zipname in compression "+zipname);
    GZIPOutputStream zipout;
    try {
      FileOutputStream out = new FileOutputStream(zipname);
      zipout = new GZIPOutputStream(out);
    }
    catch (IOException e) {
      System.out.println("Couldn't create " + zipname + ".");
      return;
    }
    byte[] buffer = new byte[bufferSize];
    // compress the file
    try {
      FileInputStream in = new FileInputStream(filename);
      int length;
      while ((length = in.read(buffer, 0, bufferSize)) != -1)
        zipout.write(buffer, 0, length);
      in.close(  );
    }
    catch (IOException e) {
      System.out.println("Couldn't compress " + filename + ".");
    }
    try { zipout.close(  ); }
    catch (IOException e) {}
  }

  public static void Decompress(String filename){

        System.out.println(filename);
        // create input stream
        String zipname;
        String source;
        if (filename.endsWith(".gz")) {
            zipname = filename;
            source = filename.substring(0, filename.length() - 3);
            System.out.println("this is source "+source);
            GZIPInputStream zipin;
            try {
                    FileInputStream in = new FileInputStream(zipname);
                    zipin = new GZIPInputStream(in);
            }
            catch (IOException e) {
                    System.out.println("Couldn't open " + zipname + ".");
            return;
            }
            byte[] buffer = new byte[bufferSize];
            // decompress the file
            try {
                    FileOutputStream out = new FileOutputStream(source+".xml");
                    int length;
                    while ((length = zipin.read(buffer, 0, bufferSize)) != -1)
                        out.write(buffer, 0, length);
                    out.close(  );
            }
            catch (IOException e) {
                    System.out.println("Couldn't decompress " + filename + ".");
            }
            try { zipin.close(  ); }
            catch (IOException e) {}


        }else {
             System.out.println("This is not a compressed file");
        }
  }

}
